package com.gcxy.service.impl;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gcxy.conf.result.R;
import com.gcxy.conf.result.ResultCodeEnum;
import com.gcxy.dto.AddUserDTO;
import com.gcxy.dto.EditUserDTO;
import com.gcxy.dto.LoginUserDTO;
import com.gcxy.dto.UserPageDTO;
import com.gcxy.entity.SequenceTable;
import com.gcxy.entity.User;
import com.gcxy.mapper.UserMapper;
import com.gcxy.service.ISequenceTableService;
import com.gcxy.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gcxy.utils.Md5Utils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * <p>
 * 用户表; 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-12-25
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ISequenceTableService sequenceTableService;

    @Override
    public R login(LoginUserDTO loginUserDTO) {
        //查询账号是否重复
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(User::getUserId,loginUserDTO.getUserId());
        User accountOne = getOne(queryWrapper);
        if(ObjectUtils.isEmpty(accountOne))
        {
            return R.Failed(ResultCodeEnum.REQUEST_PARAM_ERROR.getCode(),"账号不存在！");
        }
        queryWrapper.eq(User::getPassword, Md5Utils.hash(loginUserDTO.getPassword()));
        accountOne=getOne(queryWrapper);
        if(ObjectUtils.isEmpty(accountOne))
        {
            return R.Failed(ResultCodeEnum.REQUEST_PARAM_ERROR.getCode(),"密码错误，请重新输入！");
        }
        if (accountOne.getUserStatus()!=1){
            return R.Failed("账号已禁用，无法登录！");
        }
//        String token = null;
//        try {
//            token = JWTSecurityUtil.buildJWT(accountOne.getUserId(), 60 * 24);
//        } catch (JOSEException e) {
//            throw new RuntimeException(e);
//        }
//        String accountOneJsonString =JSON.toJSONString(accountOne);
//        redisTemplate.opsForValue().set(token,accountOneJsonString,  60 * 24, TimeUnit.MINUTES);
        // 第1步，先登录上
        StpUtil.login(accountOne.getUserId());
        LocalDateTime now = LocalDateTime.now();
        accountOne.setUpdateTime(now);
        updateById(accountOne);
        // 第2步，获取 Token  相关参数
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        // 第3步，返回给前端
        return R.Success(tokenInfo);
    }

    @Override
    public R logout() {
        // 执行退出登录操作
        StpUtil.logout();
        // 返回成功的响应
        return R.Success("成功退出");
    }

    @Override
    public R getCurrentUser() {
        Object userIdObj = StpUtil.getLoginId();
        String userId = (String) userIdObj;
        // 尝试根据用户ID获取用户信息
        User user = this.getById(userId);
        if (ObjectUtils.isEmpty(user)) {
            // 如果找不到用户信息，返回失败的响应（这里假设getById在找不到用户时返回null）
            return R.Failed("用户不存在");
        }
        // 返回成功的响应和用户信息
        return R.Success(user);
    }

    @Override
    public R addUser(AddUserDTO addUserDTO) {
        // 检查用户名和手机号是否已存在
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName, addUserDTO.getUserName());
        User existingUserByUserName = getOne(queryWrapper);

        queryWrapper.clear(); // 清空条件
        queryWrapper.eq(User::getUserPhone, addUserDTO.getUserPhone());
        User existingUserByPhone = getOne(queryWrapper);

        if (!ObjectUtils.isEmpty(existingUserByUserName)) {
            return R.Failed("用户名已存在");
        }
        if (!ObjectUtils.isEmpty(existingUserByPhone)) {
            return R.Failed("手机号已存在");
        }

        Object userIdObj = StpUtil.getLoginId();
        String userId = (String) userIdObj;
        // 创建新用户
        User newUser = new User();
        BeanUtils.copyProperties(addUserDTO, newUser);

        // 生成登录账号
        String sequenceNumberStr = sequenceTableService.getMaxSequenceNumber();

        // 尝试将字符串解析为整数
        try {
            int sequenceNumber = Integer.parseInt(sequenceNumberStr); // 这里假设序列号字符串是可以解析为整数的
            // 对序列号进行递增操作
            int newSequenceNumber = sequenceNumber + 1;
            String newUserId = "YZ" + String.format("%04d", newSequenceNumber);
            // 设置新用户ID
            SequenceTable sequenceTable = new SequenceTable();
            sequenceTable.setCurrentSequence(String.format("%04d", newSequenceNumber));
            sequenceTableService.save(sequenceTable);
            newUser.setUserId(newUserId);
        } catch (NumberFormatException e) {
            System.err.println("无法解析序列号字符串: " + sequenceNumberStr);
        }

        // 设置默认密码为手机号后6位
        String defaultPassword = addUserDTO.getUserPhone().substring(addUserDTO.getUserPhone().length() - 6);
        newUser.setPassword(Md5Utils.hash(defaultPassword));
        LocalDateTime now = LocalDateTime.now();
        newUser.setCreateTime(now);
        newUser.setCreater(getById(userId).getUserName());
        // 保存新用户
        save(newUser);
        return R.Success(newUser);
    }

    @Override
    public R deleteUser(String userId) {
        removeById(userId);
        return R.Success("删除成功");
    }

    @Override
    public R resetPassword(String userId) {
        System.out.println(userId);
        User user = this.getById(userId);
        String password = Md5Utils.hash("123456");
        user.setPassword(password);
        LocalDateTime now = LocalDateTime.now();
        user.setUpdateTime(now);
        user.setUpdater(user.getUserName());
        updateById(user);
        return R.Success(user);
    }

    @Override
    public R editUser(EditUserDTO editUserDTO) {
        User user=this.getById(editUserDTO.getUserId());
        BeanUtils.copyProperties(editUserDTO, user);
        LocalDateTime now = LocalDateTime.now();
        user.setUpdateTime(now);
        user.setUpdater(user.getUserName());
        updateById(user);
        return R.Success("修改成功");
    }

    @Override
    public R getUserList(UserPageDTO userPageDTO) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.like(userPageDTO.getUserName()!=null,User::getUserName,userPageDTO.getUserName())
                .like(userPageDTO.getUserPhone()!=null,User::getUserPhone,userPageDTO.getUserPhone())
                .eq(userPageDTO.getUserStatus()!=null,User::getUserStatus,userPageDTO.getUserStatus());
        Page<User> userPage=new Page<>(userPageDTO.getPageNumber(),userPageDTO.getPageSize());
        userPage=page(userPage,queryWrapper);
        return R.Success(userPage);
    }
}
